<template>
  <div>
 
   <div style="margin: 10px;">
     <!-- <el-input v-model="userId" suffix-icon="el-icon-search" placeholder="请输入用户ID" style="width: 200px;" @keyup.enter.native="queryData"></el-input>
     <el-button  type="primary" style="margin-left: 5px;" @click="queryData">查询</el-button> -->
     <!-- <el-button type="success" @click="reset">重置</el-button> -->
 
     <el-button  type="primary" style="margin-left: 5px;" @click="add" plain>新增</el-button>
     <el-button type="danger" @click="batchDelete" :disabled="this.sels.length === 0" plain>批量删除</el-button>
   </div>
 
   <el-table :data="tableData"
     :header-cell-style="{background:'#f2f5fc',color: '#555555',textAlign:'center'}"
     border
     @selection-change="handleSelectionChange"
     :row-key="getRowKeyOfTarget"
     :cell-style="{textAlign:'center'}"
   >

         <!-- 选框 -->
         <el-table-column 
          type="selection" 
          width="40"
          :reserve-selection="true" 
        ></el-table-column>

         <el-table-column prop="roleId" label="角色ID" width="60">
         </el-table-column>
 
         <el-table-column prop="roleName" label="角色名" width="90">
         </el-table-column>
 
         <el-table-column prop="permissionIdList" label="权限ID集合" width="120">
         </el-table-column>
 
         <el-table-column prop="permissionNameList" label="权限名集合" show-overflow-tooltip :style="{'white-space':'nowrap'}" width="120px">
         </el-table-column>

         <el-table-column prop="warehouseIdList" label="所选仓库ID集合" width="120">
         </el-table-column>
 
         <el-table-column prop="warehouseNameList" label="所选仓库名集合" show-overflow-tooltip :style="{'white-space':'nowrap'}" width="120px">
         </el-table-column>

         <el-table-column prop="requestProcessingList" label="所选仓库ID审批权限集合" width="120px">
         </el-table-column>
 
         <el-table-column prop="description" label="角色描述" width="80px">
         </el-table-column>
         
         <el-table-column prop="operate" label="操作" >
 
           <template slot-scope="scope">

            <div class="action-buttons">
            <span class="edit-link" @click="mod(scope.row)">
              <i class="el-icon-edit"></i> 编辑
            </span>

            <el-popconfirm title="确定删除吗?" @confirm="handleDelete(scope.row.roleId)" style="margin-left: 5px;">
             <template #reference>
              <span class="delete-link">
              <i class="el-icon-delete"></i> 删除
            </span>
             </template>
           </el-popconfirm>
          </div>

             <!-- <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
           <el-popconfirm title="确定删除吗?" @confirm="handleDelete(scope.row.roleId)" style="margin-left: 5px;">
             <template #reference>
               <el-button
                 size="small"
                 type="danger"
               >删除</el-button>
             </template>
           </el-popconfirm> -->

          </template>
         
 
         </el-table-column>
       </el-table>
<!--  
       <el-pagination
       @size-change="handleSizeChange"
       @current-change="handleCurrentChange"
       :current-page.sync="pageNum"
       :page-sizes="[5, 10, 20,30]"
       :page-size="pageSize"
       layout="total, sizes, prev, pager, next, jumper"
       :total="total"
       style="margin-top: 5px;">
     </el-pagination>
  -->
     

     <!-- 新增 -->
     <el-dialog
       title="提示"
       :visible.sync="centerDialogVisible"
       :before-close="handleClose"
       center>
       <el-form ref="form" :rules="rules" :model="form" label-width="120px">
        
         <el-form-item label="角色ID" prop="roleId" style="display: none;">
          <el-col :span="20">
           <el-input v-model="form.roleId"></el-input>
          </el-col>
         </el-form-item>
 
         <el-form-item label="角色名" prop="roleName">
          <el-col :span="20">
           <el-input v-model="form.roleName"></el-input>
          </el-col>
         </el-form-item>
 
         <!-- <el-form-item label="角色权限" prop="permissionIdList" >
          <el-select v-model="form.permissionIdList" multiple>
          <el-option v-for="role in permissionIdOptions" :key="role.permissionId" :label="role.permissionName" :value="role.permissionId">
          </el-option>
        </el-select>
         </el-form-item> -->

         <el-table :data="permissionData" border style="width: 100%;max-height: 200px; overflow-y: auto;margin: 5px;"
         :header-cell-style="{background:'#f2f5fc',color: '#555555',textAlign:'center'}"
         :cell-style="{textAlign:'center'}">
              <el-table-column label="角色权限ID" v-if="showColumn">
                  <template slot-scope="scope">
                       {{ scope.row.permissionId }}
                   </template>
              </el-table-column>

             <el-table-column label="角色权限名称">
                <template slot-scope="scope">
                   {{ scope.row.permissionName }}
                </template>
            </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-checkbox v-model="scope.row.checked" @change="handlePermissionChange(scope.row)"></el-checkbox>
        </template>
      </el-table-column>
    </el-table>

         <el-table 
         :data="wareData" 
         border 
         style="width: 100%;max-height: 200px; overflow-y: auto;margin: 5px;" 
         :header-cell-style="{background:'#f2f5fc',color: '#555555',textAlign:'center'}"
         :cell-style="{textAlign:'center'}">
           <el-table-column label="仓库ID" prop="warehouseId" v-if="showColumn"></el-table-column>
           <el-table-column label="仓库名称" prop="warehouseName"></el-table-column>
           <el-table-column label="访问权限">
         <template slot-scope="scope">
           <el-checkbox v-model="scope.row.accessPermission" @change="handleAccessPermissionChange(scope.row)"  ></el-checkbox>
         </template>
       </el-table-column>
      <el-table-column label="审批权限">
        <template slot-scope="scope">
          <el-checkbox v-model="scope.row.approvalPermission" @change="handleApprovalPermissionChange(scope.row)" :disabled="!scope.row.accessPermission"></el-checkbox>
        </template>
      </el-table-column>
    </el-table>
  
 
         <el-form-item label="角色描述" prop="description">
          <el-col :span="20">
           <el-input v-model="form.description"></el-input>
          </el-col>
         </el-form-item>
       </el-form>
 
       <span slot="footer" class="dialog-footer">
         <el-button @click="centerDialogVisible = false">取消</el-button>
         <el-button type="primary" @click="save">确定</el-button>
       </span>
     </el-dialog>

     <!-- 修改 -->
     <el-dialog
       title="提示"
       :visible.sync="centerDialogVisible1"
       :before-close="handleClose"
       center>
       <el-form ref="form1" :rules="rules1" :model="form1" label-width="120px">
        
         <el-form-item label="角色ID" prop="roleId" style="display: none;">
          <el-col :span="20">
           <el-input v-model="form1.roleId"></el-input>
          </el-col>
         </el-form-item>
 
         <el-form-item label="角色名" prop="roleName">
          <el-col :span="20">
           <el-input v-model="form1.roleName"></el-input>
          </el-col>
         </el-form-item>
 
         <el-form-item label="角色权限" prop="permissionIdList" >
          <el-select v-model="form1.permissionIdList" multiple>
          <el-option v-for="role in permissionIdOptions" :key="role.permissionId" :label="role.permissionName" :value="role.permissionId">
          </el-option>
        </el-select>
         </el-form-item>

         <el-form-item label="所选仓库ID集合" prop="warehouseIdList" >
          <el-select v-model="form1.warehouseIdList" multiple>
          <el-option v-for="role in warehouseIdList" :key="role.warehouseIdList" :label="role.warehouseName" :value="role.warehouseIdList">
          </el-option>
        </el-select>
         </el-form-item>

         <el-form-item label="所选仓库ID审批权限集合" prop="requestProcessingList" >
          <el-select v-model="form1.requestProcessingList" multiple>
          <el-option v-for="role in requestProcessingList" :key="role.requestProcessingList" :label="role.requestProcessingList" :value="role.requestProcessingList">
          </el-option>
        </el-select>
         </el-form-item>
 
         <el-form-item label="角色描述" prop="description">
          <el-col :span="20">
           <el-input v-model="form1.description"></el-input>
          </el-col>
         </el-form-item>
       </el-form>
 
       <span slot="footer" class="dialog-footer">
         <el-button @click="centerDialogVisible1 = false">取消</el-button>
         <el-button type="primary" @click="save1">确定</el-button>
       </span>
     </el-dialog>
 
  </div>
 </template>
 
 <script>
 export default {
   name: "Main",
  
   data() {
       return {
        permissionIdOptions:[],
        wareData:[
      // {
			// "requestProcessing": "否",
			// "roleId": 1,
			// "rwId": 0,
			// "warehouseId": 2,
			// "warehouseName": "仓库A"
		  // },
      // {
			// "requestProcessing": "否",
			// "roleId": 1,
			// "rwId": 0,
			// "warehouseId": 3,
			// "warehouseName": "仓库B"
		  // },
  ],
        permissionData: [],
        "accessPermission": false, // 新增属性：访问权限
        "approvalPermission": false, // 新增属性：审批权限
      //   wareData:[
      //   {
      //     "description": "对仓库的商品进行管理和调度",
      //     "permissionIdList": [1, 2],
      //     "permissionNameList": ["添加用户", "修改用户"],
      //     "requestProcessingList": ["是"],
      //     "roleId": 2,
      //     "roleName": "仓管",
      //     "warehouseIdList": [1,2,3,4,5,6,7],
      //     "warehouseNameList": ["仓库A","仓库B","仓库C","仓库d","仓库e","仓库f","仓库g"]
      //   }
      // ],
        // 隐藏某一列
        showColumn: false,
        roleId:0,
         // 当前选框中的值
         sels: [],
         // 每页多少条
         pageSize:10,
         // 当前页
         pageNum:1,
         name:'',
         vendorName:'',
         total:0,
         tableData: [{
           userId:"1",
           userName:"111",
           address: 1,
           email: 111,
           telephone:2222,
           status:1,
           created:'',
           updated:'',
           imgUrl:''
 
         }],
         centerDialogVisible: false,
         centerDialogVisible1: false,
         form:{
            roleId:0,
            roleName:'',
            description:'',
            permissionIdList:[],
            warehouseIdList:[],
            requestProcessingList:[],
         },
         form1:{
           roleId:0,
            roleName:'',
            permissionIdList:[],
            requestProcessingList:[],
            warehouseIdList:[],
            description:''
         },
         permissionIdList:[],
         warehouseIdList:[],
         requestProcessingList:[],
         rules: {
          roleId: [
               { required: true, message: '请输入角色ID', trigger: 'blur' },
              //  { min: 1, max: 5, message: '长度在1到8个字符', trigger: 'blur' },
           ],
           roleName:[
           { required: true, message: '请输入角色名', trigger: 'blur' },
           ],
           permissionIdList:[
           { required: true, message: '请输入权限ID集合', trigger: 'blur' },
           ],
           warehouseIdList:[
           { required: true, message: '请输入所选仓库ID集合', trigger: 'blur' },
           ],
           requestProcessingList:[
           { required: true, message: '请输入所选仓库ID审批权限集合', trigger: 'blur' },
           ],
           permissionNameList:[
           { required: true, message: '请输入权限名集合', trigger: 'blur' },
           ],
           description:[
           { required: true, message: '请输入角色描述', trigger: 'blur' },
           ]
         },
         rules1: {
          roleId: [
               { required: true, message: '请输入角色ID', trigger: 'blur' },
              //  { min: 1, max: 5, message: '长度在1到8个字符', trigger: 'blur' },
           ],
           roleName:[
           { required: true, message: '请输入角色名', trigger: 'blur' },
           ],
           permissionIdList:[
           { required: true, message: '请输入权限ID集合', trigger: 'blur' },
           ],
           permissionNameList:[
           { required: true, message: '请输入权限名集合', trigger: 'blur' },
           ],
          //  warehouseIdList:[
          //  { required: true, message: '请输入所选仓库ID集合', trigger: 'blur' },
          //  ],
          //  requestProcessingList:[
          //  { required: true, message: '请输入所选仓库ID审批权限集合', trigger: 'blur' },
          //  ],
           description:[
           { required: true, message: '请输入角色描述', trigger: 'blur' },
           ]
         },
         
       }
     },

     computed: {
    // filteredWareData() {
    //   let result = [];
    //   this.wareData.forEach(item => {
    //     for (let i = 0; i < item.warehouseIdList.length; i++) {
    //       result.push({
    //         warehouseId: item.warehouseIdList[i],
    //         warehouseName: item.warehouseNameList[i]
    //       });
    //     }
    //   });
    //   return result;
    // }
  },
   methods:{
    handlePermissionChange(permission) {
      // 处理权限复选框改变事件
      console.log("Permission Changed:", permission.permissionName, permission.checked);
      if(permission.checked){
        this.permissionIdList.push(permission.permissionId)
        console.log("Permission array:",this.permissionIdList);
        this.form.permissionIdList.push(permission.permissionId)
        console.log("form.permissionIdList",this.form.permissionIdList);
      }else{
        // 如果取消选中复选框，则从数组中移除对应的permissionId
        const index = this.permissionIdList.indexOf(permission.permissionId)
        if(index !== -1){
          this.form.permissionIdList.splice(index,1)
          console.log("form.permissionIdList",this.form.permissionIdList);
        }
      }
    },
    handleAccessPermissionChange(row) {
      // 处理访问权限改变事件
      if(row.accessPermission){
         // 如果访问权限被给予，将仓库ID存入数组中
         this.form.warehouseIdList.push(row.warehouseId)
         console.log("this.form.warehouseIdList",this.form.warehouseIdList);
      }else{
         // 如果访问权限被取消，从数组中移除仓库ID
         const index = this.form.warehouseIdList.indexOf(row.warehouseId)
         if(index !== -1){
           this.form.warehouseIdList.splice(index,1)
         }
         // 同时取消审批权限
         row.approvalPermission = false
      }
    },
    handleApprovalPermissionChange(row){
        if (!row.accessPermission) {
        // 如果没有访问权限，则不允许给予审批权限
        row.approvalPermission = false;
      return;
    }
    // 处理审批权限的更新，可以将审批状态存入数组中
    if (row.approvalPermission) {
      // this.approvalPermissionList.push("是");
      this.form.requestProcessingList.push("是")
      console.log("this.form.approval",this.form.requestProcessingList);
    } else {
      const index = this.form.warehouseIdList.indexOf(row.warehouseId)
         if(index !== -1){
           this.form.requestProcessingList.splice(index,1)
         }
      // this.approvalPermissionList.push("否");
      this.form.requestProcessingList[index] = "否"
      console.log("approval",this.form.requestProcessingList);
    }
    },
     // 重置表单
     resetForm(){
       this.$refs.form.resetFields();
     },
 
     // 当前页，每页几条发生改变时
    handleSizeChange(val) {
         this.pageNum = 1
         this.pageSize=val
         console.log(`${val} items per page`);
         this.loadPost()
       },
    handleCurrentChange(val) {
         // 设置当前页
         this.pageNum = val
         // 查询
         this.loadPost()
         console.log(`current page: ${val}`);
       },
      
     // 获取入库页面数据
     loadPost(){
       this.$axios.get('/api/role/list').then(res => {
         console.log(res);
         if(res.data.code == "200"){
           this.tableData = res.data.data
           this.total = res.data.data.total
         } 
 
       })
     },
 
     // 重置数据
     reset(){
       this.roleId = ""
       this.loadPost()
     },
 
     // 新增
     add(){
       this.centerDialogVisible = true
       this.$nextTick(() => {
         this.resetForm();
    //      // 重置访问权限和审批权限为原始状态
    //   this.wareData.forEach(item => {
    //   item.accessPermission = false;
    //   item.approvalPermission = false;
    // });
    //   this.permissionData.forEach(item =>{
    //     item.checked = false
    //   })
       })
     },
     // 确认关闭模态框
     handleClose(done) {
         this.$confirm('Are you sure to close this dialog?')
           .then(_ => {
             done();
           })
           .catch(_ => {});
       },
     // 新增
     doSave(){
      console.log('the form is:');
      console.log(this.form);
       this.$axios.post('/api/role/add',
     this.form).then(res => {
       console.log(res);
       if(res.data.code == "200"){
         this.loadPost();
         this.centerDialogVisible = false
         // alert("成功")
         this.$message({
           message: '更新成功',
           type: 'success'
         })
         
       } else{
         // alert("失败")
         this.$message({
           message:"操作失败",
           type:"error"
         })
       }
       })
     },
     // 修改
     doMod(){
       this.$axios.post("/api/role/update",this.form1).then(res => {
         console.log(res);
         if(res.data.code == '200'){
          this.$message({
            type:"success",
            message:"修改成功"
          })
          this.centerDialogVisible1 = false
          this.loadPost()
         }else{
          this.$message({
            type:"error",
            message:"修改失败"
          })
         }
       })
     },
     save1(){
      this.doMod()
     },
     // 新增或者修改时时保存
     save(){
      // this.doSave()
       this.$refs.form.validate((valid) => {
           if (valid) {
             if(this.form.roleId){
               // 修改
               this.doMod()
             }else{
               // 新增
               this.doSave();
             }
      
           } else {
             console.log('error submit!!');
             return false;
           }
         });
 
       
     },
 
      // 删除
      handleDelete(id){
       console.log(id);
       this.$axios.delete("/api/role/delete/" + id).then(res => {

         console.log(res);
         if(res.data.code == '200'){
           this.$message({
           type:"success",
           message:"删除成功"
         })
         }else{
           this.$message({
           type:"error",
           message:"删除失败"
         })
         }
         this.loadPost()  // 删除之后重新加载表格的数据
 
       })
     },
 
     // 编辑
     mod(row){
       console.log(row);
      
       // 先打开再异步处理
       this.centerDialogVisible1 = true
       this.$axios.get("/api/role_permission/list",{
        params:{
          roleId:row.roleId
        }
       }).then((res) =>{
        this.form1.permissionIdList = res.data.data.map(role => role.permissionId)
       })
 
       this.$nextTick(() => {
          // 赋值到表单
          this.form1.description = row.description
          this.form1.roleId = row.roleId
          this.form1.roleName = row.roleName
         
       })
     },
     
      // 批量删除
     // 获取选中的值
     handleSelectionChange(sels){
      this.sels = sels;
      console.log("选中的值",sels.map((item) => item.roleId));
      
     },
     // 批量删除执行操作
     batchDelete(){
      // 删除的提示
      let count = this.sels.length;
      this.$confirm("确认删除这"+ count +"记录吗？","提示",{
        type:"warning"
      }).then(() => {
        // const idList = []
        // for(const v of this.sels){
        //   idList.push(v.id)
        // }
        // console.log(idList);
        let ids = this.sels.map((item) => item.roleId)
        console.log(111222);
        // console.log(JSON.stringify(ids));
        console.log(ids);

        // 请求接口
        this.$axios.delete("/api/role/batch_delete/",
        { 
          data: ids, // 将数组数据作为请求体发送 
          headers: { 'Content-Type': 'application/json' } 
        }
        
        ).then(res =>{
          console.log(res);
          if(res.data.code == '200'){
            this.$message({
            message:"批量删除成功",
            type:"success"
          })
          this.loadPost()
          }else{
            this.$message({
              message:"批量删除失败",
              type:"error"
            }).catch((e)=>{
              console.log(e);
            })
          }
          // console.log(1111);/*  */
        
          // if(res.data.code == '200'){
          //   this.$message({
          //   message: "删除成功",
          //   type: "success"
          // })
          //   this.loadPost()
          // }else{
          //   this.$message({
          //     message:"删除失败",
          //     type:"error"
          //   })
          // }
         
        })
      }).catch((e) =>{
        console.log(e);
      })
     },
      // 设置唯一的row-key
      getRowKeyOfTarget(row) {
      return row.userId
        },

      // 根据用户id进行查询
      queryData(){
        this.$axios.get("/api/role/list/" + this.userId).then((res) => {
          console.log(this.userId);
          console.log(res);
          // this.loadPost();
          this.tableData = []
          // console.log(Object.entries(res.data.data));
          // 请求成功时将用户信息添加到userData数组
          this.tableData.push(res.data.data)
          // this.tableData = res.data.data

        })
      },
      getPermission(){
        this.$axios.get("/api/permission/list"
        ).then((res) =>{
          console.log(res);
          // this.roleOptions.push(res.data.data.roleId)
          this.permissionIdOptions = res.data.data
          // for(let v in res.data){
          //   this.roleOptions.push(v.roleId)
          // }
          console.log(111);
          console.log(this.permissionIdOptions);

        })
      },
      getAllWare(){
        this.$axios.get("/api/role_warehouse/list").then((res) =>{
          console.log('所有角色仓库关系数据');
          console.log(res);
          this.wareData = res.data.data
        })
      }

     },

  
   beforeMount() {
     this.loadPost()
    //  console.log(11111111111);
     this.getPermission()
     console.log(2222222222222222223);
     this.getAllWare()
   },
   created() {
    // 模拟接收到的数据
    const responseData = {
      "code": 200,
      "data": [
        {
          "description": "对仓库的商品进行管理和调度",
          "permissionIdList": [1, 2],
          "permissionNameList": ["添加用户", "修改用户"],
          "requestProcessingList": ["是"],
          "roleId": 2,
          "roleName": "仓管",
          "warehouseIdList": [1],
          "warehouseNameList": ["仓库A"]
        }
      ],
      "message": "操作成功",
      "status": "success"
    };
    this.$axios.get("/api/permission/list"
        ).then((res) =>{
          console.log(11111111111111111111111111111111111);
          console.log(res);
           // 将接收到的数据转换为适合表格显示的格式
           const responseData = res.data
     // 将接收到的数据转换为适合表格显示的格式
    this.permissionData = responseData.data.map(permission => ({
      permissionId: permission.permissionId, // 隐藏的权限ID
      permissionName: permission.permissionName,
      checked: false, // 默认不选中
    }));
         
        }),
        this.$axios.get("/api/role_warehouse/list"
        ).then((res) =>{
          console.log(22222222222222);
          console.log(res);
           // 将接收到的数据转换为适合表格显示的格式
           const responseData = res.data
     // 将接收到的数据转换为适合表格显示的格式
    this.wareData = responseData.data.map(permission => ({
      permissionId: permission.permissionId, // 隐藏的权限ID
      permissionName: permission.permissionName,
      checked: false, // 默认不选中
    }));
         
        })
    
   }
 }
 </script>
 
 <style scoped>
      /* 将编辑和删除按钮放在同一行 */
      .action-buttons {
       display: flex;
       align-items: center;
       justify-content: center; /* 让子元素水平居中 */
    }

   .edit-link,
   .delete-link {
       color: #6699CC;
       text-decoration: underline;
       cursor: pointer;
       margin-right: 10px;
   }

   .edit-link:hover,
   .delete-link:hover {
      color: #99CCFF;
   }

   /* 设置超过一定长度的文本显示省略号 */
   .el-table .cell {
    overflow: hidden;
    text-overflow: ellipsis;
}
 </style>